package pe.gob.essalud.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import pe.gob.essalud.model.Perfil;
import pe.gob.essalud.service.PerfilService;

@ControllerAdvice
public class CommonControllerAdvice {

	@Autowired
	private PerfilService perfilService;
	
	static final Logger LOGGER = LoggerFactory
			.getLogger(MantenerUsuariosController.class);

	@ExceptionHandler(AccessDeniedException.class)
	public String ignorarAccesoDenegado(Exception exception) {
		return "redirect:/403";
	}
	
	@ExceptionHandler(Exception.class)
	public ModelAndView handleError(HttpServletRequest req, Exception exception) {
		LOGGER.error("Request: " + req.getRequestURL() + " raised " + exception);
		StringWriter sw = new StringWriter();
		exception.printStackTrace(new PrintWriter(sw));
		LOGGER.error("Stack: " + sw.toString());
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", exception);
		mav.addObject("url", req.getRequestURL());
		mav.setViewName("500");
		return mav;
	}

	@ModelAttribute("listaPerfiles")
	public List<Perfil> getListaPerfiles() {
		return perfilService.buscarTodos();		
	}
	

}
